#!/usr/bin/env python

import logging
import __init__ as procs
import StringIO
import datetime
import os
import os.path
from PIL import Image
from PIL import ImageFont, ImageDraw

class pil_image_creator(procs.null_processor):
   def process(self, data, ts, state):
      logging.debug("CreatePILImage")
      datastream = StringIO.StringIO(data)
      return (Image.open(datastream), ts, state)

class pil_time_stamper(procs.null_processor):

   def __init__(self, config):
      procs.null_processor.__init__(self, config)
      font_name = self.config['font']
      font_type = self.config['font#type']
      tmp = self.config['font#size']
      if tmp:
         font_size = int(self.config['font#size'])
      else:
         font_size = 0

      if (font_name==None):
         self.font = ImageFont.load_default()
      elif (font_type.lower() == "truetype"):
         self.font = ImageFont.truetype(font_name, font_size)
      else:
         self.font = ImageFont.load(font_name)
   
   def process(self, data, ts, state):
      logging.debug("TimeStampImage")
      draw = ImageDraw.Draw(data)
      text = ts.strftime("%d %b %y %H:%M:%S")
      (text_width, text_height) = self.font.getsize(text)
      (img_width, img_height)   = data.size

      coordinates = (img_width - 20 - text_width,
                     img_height - 20 - text_height)

      draw.text(coordinates, text, font=self.font)
      return (data, ts, state)

class pil_mode_convert(procs.null_processor):
   def process(self, data, ts, state):
      logging.debug("ModeConvert")
      return (data.convert("RGB"), ts, state)

class pil_image_saver(procs.null_processor):
   def __init__(self, config):
      procs.null_processor.__init__(self, config)
      self.basepath = os.path.abspath(config['directories/frame'])

   def process(self, data, ts, state):
      logging.debug("SaveImage")
      filename = os.path.join(self.basepath,
                              "frame-%s.jpg" % ts.strftime("%Y%j-%H%M%S"))
      data.save(filename)
      return (data, ts, state)

class pil_montage(procs.null_processor):
   def __init__(self, xconfig):
      procs.null_processor.__init__(self, xconfig)
      self.frame_dir = os.path.abspath(self.config['directories/frame'])
      self.movie_dir = os.path.abspath(self.config['directories/rollup'])
      self.height = int(self.config['montage#height'])
      self.width = int(self.config['montage#width'])
      self.cols = int(self.config['montage#cols'])
      self.rows = int(self.config['montage#rows'])

   def __get_scaled_image(self, filename):
      image = Image.open(os.path.join(self.frame_dir, filename))
      image.thumbnail((self.width, self.height), Image.ANTIALIAS)
      return image

   def process(self, data, ts, state):
      files = filter(lambda x: x[:5] == "frame", os.listdir(self.frame_dir))
      files.sort()
      numfiles = len(files)
      images = [ ]
      for file in files:
         images.append(self.__get_scaled_image(file))

      (width, height) =  images[0].size
      newwidth = width * self.cols
      newheight = height * self.rows

      new_image = Image.new("RGB", (newwidth, newheight))
      location = [ 0, 0 ]
      for image in images:
         new_image.paste(image,(location[0]*width, location[1]*height))
         location[0] += 1
         if location[0] >= self.cols:
            location[0] = 0
            location[1] += 1

      data = os.path.join(self.movie_dir, ts.strftime("montage-%Y%j-%H%M%S.jpg"))
      new_image.save(data)

      return (data, ts, state)
